

package cn.liyao.web.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import cn.liyao.tool.annotation.RequireToken;
import cn.liyao.tool.api.R;
import cn.liyao.web.holder.CurrentUserIdHolder;
import cn.liyao.web.model.Conversation;
import cn.liyao.web.model.Friend;
import cn.liyao.web.model.Group;
import cn.liyao.web.model.User;
import cn.liyao.web.repository.ConversationRepository;
import cn.liyao.web.repository.FriendRepository;
import cn.liyao.web.repository.GroupRepository;
import cn.liyao.web.repository.UserRepository;
import cn.liyao.web.vo.FriendVO;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserController {

    private final UserRepository userRepository;


    private final FriendRepository friendRepository;

    private final ConversationRepository conversationRepository;

    private final GroupRepository groupRepository;

    @Autowired
    public UserController(UserRepository userRepository, FriendRepository friendRepository,ConversationRepository conversationRepository,GroupRepository groupRepository) {
        this.userRepository = userRepository;
        this.friendRepository = friendRepository;
        this.conversationRepository = conversationRepository;
        this.groupRepository = groupRepository;
    }


    @Value("${jwt.token}")
    private String jwtToken;




    @GetMapping("/refreshSingleConversationByGroupId")
    @RequireToken()
    public  R refreshSingleConversationByGroupId(String targetId){

         Optional<Group> groupOptional  =  groupRepository.findById(targetId);

         if(!groupOptional.isPresent()) return R.fail("群不存在");
         Group group = groupOptional.get();

         Map map = new HashMap();
         map.put("userPortrait",group.getPortrait());
         map.put("userName", group.getGroupName());
        return R.data(map);
    }



    @GetMapping("/refreshSingleConversationByUserId")
    @RequireToken()
    public  R refreshSingleConversationByUserId(String targetId){
        String userId = CurrentUserIdHolder.getCurrentUser();
        Friend friend = friendRepository.findFirstByUserIdAndFriendId(userId,targetId);
        Optional<User> user = userRepository.findById(targetId);

        FriendVO friendVO = new FriendVO();
        BeanUtils.copyProperties(user.get(),friendVO);
        friendVO.setRemark(friend.getRemark());
        friendVO.setAddTime(friend.getAddTime());

        // 这里应该异步处理
        Conversation conversation =conversationRepository.findOneByUserIdAndTargetId(userId,targetId);

        if(conversation != null){

            if(conversation.getPortrait() == null){
                conversation.setPortrait("");
            }

            if(friendVO.getRemark() != null){
                if(!conversation.getUserName().equals(friendVO.getRemark())){
                    conversation.setUserName(friendVO.getRemark());
                }
            }


            if(ObjectUtil.isEmpty(friendVO.getRemark())){
                if(!conversation.getUserName().equals(friendVO.getNickName())){
                    conversation.setUserName(friendVO.getNickName());
                }
            }

            if(friendVO.getUserPortrait() != null){
                if(!conversation.getPortrait().equals(friendVO.getUserPortrait())){
                    conversation.setPortrait(friendVO.getUserPortrait());
                }
            }


            conversationRepository.save(conversation);

        }



        return R.data(friendVO);
    }




    @PostMapping("removeFriend")
    @RequireToken()
    public R removeFriend(String friendId) {
        String userId =  CurrentUserIdHolder.getCurrentUser();
        Friend friend =  friendRepository.findFirstByUserIdAndFriendId(userId,friendId);
        if(friend == null){
            return R.fail("设置失败");
        }
        friend.setState(1);
        friendRepository.save(friend);

        // 顺便把这个会话删了

        Conversation conversation = conversationRepository.findOneByUserIdAndTargetId(userId,friendId);

        if(conversation != null){
            conversationRepository.deleteById(conversation.getId());
        }


        return R.success("修改成功");
    }



    @PostMapping("setRemarks")
    @RequireToken()
    public R setRemarks(@RequestBody Map map) {

        String remark = map.get("remark").toString();
        String friendId = map.get("friendId").toString();
        String userId =  CurrentUserIdHolder.getCurrentUser();

        Friend friend =  friendRepository.findFirstByUserIdAndFriendId(userId,friendId);
        if(friend == null){
            return R.fail("设置失败");
        }


        friend.setRemark(remark);
        friendRepository.save(friend);


        return R.success("修改成功");
    }




    @PostMapping("/updateAvatar")
    @RequireToken()
    public R updateAvatar(@RequestBody Map map) {
        String userId =  CurrentUserIdHolder.getCurrentUser();
        Optional<User> db =  userRepository.findById(userId);
        User user = db.get();
        user.setUserId(userId);
        user.setUserPortrait(map.get("url").toString());
        userRepository.save(user);
        return R.data("修改成功");
    }


    @PostMapping("/updateInfo")
    @RequireToken()
    public R updateInfo(@RequestBody Map map) {
        String userId =  CurrentUserIdHolder.getCurrentUser();

        Optional<User> db =  userRepository.findById(userId);
        User user = db.get();
        user.setUserId(userId);
        user.setNickName(map.get("nickName").toString());
        user.setGender(User.Gender.valueOf(map.get("gender").toString()));
        user.setSignature(map.get("signature").toString());
        userRepository.save(user);
        return R.data("修改成功");
    }




    @GetMapping("/findUserById")
    @RequireToken()
    public R findUserById(String id) {
        Optional<User> user = userRepository.findById(id);
        if (!user.isPresent()) return R.fail("用户不存在");
        return R.data(user.get());
    }




    @GetMapping("/getUser")
    @RequireToken()
    public R getUser(String userName) {
        String userId =  CurrentUserIdHolder.getCurrentUser();
        User user = userRepository.findByUserName(userName);
        if (user == null) return R.fail("用户不存在");
        Friend friend =  friendRepository.findFirstByUserIdAndFriendIdAndState(userId, user.getUserId(),0);
        if(friend != null){
            user.setRemark(friend.getRemark());
            user.setIsFriend(true);
        }
        return R.data(user);
    }

    @GetMapping("/getCurrentUser")
    @RequireToken()
    public R getCurrentUser() {
        String userId = CurrentUserIdHolder.getCurrentUser();
        Optional<User> user = userRepository.findById(userId);
        if (!user.isPresent()) return R.fail("用户不存在");
        return R.data(user.get());
    }


    @PostMapping("/login")
    @CrossOrigin()
    public R login(@RequestBody Map<String, Object> body) {
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String username = jsonObject.getStr("username");
        String password = jsonObject.getStr("password");
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return R.fail("[username] and [password] 不能用null");
        }
        User user = userRepository.findByUserName(username);
        if (ObjectUtil.isEmpty(user)) {
            User saveUser = new User();
            saveUser.setUserName(username);
            saveUser.setNickName(username);
            saveUser.setPassword(SecureUtil.md5(password));
            saveUser.setRegTime(new Date());
            saveUser.setGender(User.Gender.OTHER);
            saveUser.setProvinceCity("未知");
            saveUser.setUserId(IdUtil.getSnowflakeNextIdStr());
            user = userRepository.save(saveUser);
        } else {
            if (!StrUtil.equals(SecureUtil.md5(password), user.getPassword())) {
                return R.fail("密码错误");
            }
        }


        Map<String, Object> payload = new HashMap<String, Object>();
        payload.put("userId", user.getUserId());
        payload.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);

        String token = JWTUtil.createToken(payload, jwtToken.getBytes());


        Map<String, Object> result = new HashMap<String, Object>();
        result.put("token", token);
        result.put("user", user);

        return R.data(result);
    }


}